package com.xpec.c4.db.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.xpec.c4.service.common.ServiceConfig;

/**
 * 文件操作辅助类
 * 
 * @author Bany
 * @version 0.1
 */
public final class FileUtil {

	/**
	 * 缓存
	 */
	private static final int BUFFER = 8192;

	/**
	 * 构造函数
	 */
	private FileUtil() {
	}

	/**
	 * 创建文件夹<br/>
	 * 存在目录下有文件与文件夹名称相同，也不创建
	 * 
	 * @param dir
	 *            文件夹路径
	 * @param ignoreIfExitst
	 *            是否文件存在依然创建
	 * @return 是否成功
	 * @throws IOException
	 *             IO异常
	 */
	public static boolean createDir(String dir, boolean ignoreIfExitst)
			throws IOException {
		File file = new File(dir);

		if (ignoreIfExitst && file.exists()) {
			return true;
		}

		if (file.mkdir() == true)
			return true;

		else
			return false;
	}

	/**
	 * 创建文件夹
	 * 
	 * @param dir
	 *            文件夹路径
	 * @param ignoreIfExitst
	 *            是否文件存在依然创建
	 * @return 是否成创建目录
	 */
	public static boolean createDirs(String dir, boolean ignoreIfExitst) {
		File file = new File(dir);

		if (ignoreIfExitst && file.exists() && file.isDirectory()) {
			return true;
		}

		if (file.mkdirs() == true)
			return true;

		else
			return false;
	}

	/**
	 * 删除文件夹
	 * 
	 * @param dir
	 *            文件夹路径
	 * @return 创建信息
	 */
	public static String deleteDir(File dir) {
		if (dir.isFile())
			return "not a directory";

		File[] files = dir.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				File file = files[i];
				if (file.isFile()) {
					file.delete();
				} else {
					deleteDir(file);
				}
			}
		}
		return Boolean.toString(dir.delete());
	}

	/**
	 * 根据文件全路径获取文件名
	 * 
	 * @param fullFilePath
	 *            文件全路径
	 * @return 文件名
	 */
	public static String getFileName(String fullFilePath) {
		if (fullFilePath == null) {
			return "";
		}
		int index1 = fullFilePath.lastIndexOf('/');
		int index2 = fullFilePath.lastIndexOf('\\');

		// index is the maximum value of index1 and index2
		int index = (index1 > index2) ? index1 : index2;
		if (index == -1) {
			// not found the path separator
			return fullFilePath;
		}
		String fileName = fullFilePath.substring(index + 1);
		return fileName;
	}

	/**
	 * 取根目录
	 * 
	 * @return 返回根目录地址
	 */
	public static String getRootPath() {
		// if (rootPath == null) {
		// URL url = instance.getClass().getClassLoader().getResource("/");
		// File file = new File(url.getFile());
		// rootPath = file.getParentFile().getParent();
		//
		// if (!rootPath.endsWith("/") && !rootPath.endsWith(File.separator)) {
		// rootPath = rootPath + "/";
		// }
		// }
		return ServiceConfig.rootPath;
	}

	/**
	 * 保存文件
	 * 
	 * @param outDir
	 *            输出的目录
	 * @param newFileName
	 *            新的文件名
	 * @param inFile
	 *            文件
	 * @return 是否成功操作
	 */
	public static boolean saveFile(String outDir, String newFileName,
			File inFile) {
		if (inFile == null)
			return false;
		if (inFile.getName() == "")
			return false;

		if (createDirs(outDir, true)) {
			FileInputStream in;
			FileOutputStream out;
			String outPutPath = (outDir.endsWith("/") || outDir
					.endsWith(File.separator)) ? outDir + newFileName : outDir
					+ "/" + newFileName;
			try {
				in = new FileInputStream(inFile);
				out = new FileOutputStream(outPutPath);
			} catch (FileNotFoundException e1) {
				return false;
			}

			int bytesRead;
			byte[] buffer = new byte[BUFFER];

			try {
				while ((bytesRead = in.read(buffer)) > -1) {
					out.write(buffer, 0, bytesRead);
				}
			} catch (IOException e) {
				return false;
			} finally {
				try {
					in.close();
					out.close();
				} catch (IOException e2) {
				}
			}
			return true;
		} else
			return false;
	}

	/**
	 * 保存文件
	 * 
	 * @param outDir
	 *            输出的目录
	 * @param newFileName
	 *            新的文件名称
	 * @param in
	 *            内容的信息流
	 * @return 是否成功操作
	 */
	public static boolean saveFile(String outDir, String newFileName,
			InputStream in) {
		if (in == null)
			return false;

		if (createDirs(outDir, true)) {
			OutputStream out;
			String outPutPath = (outDir.endsWith("/") || outDir
					.endsWith(File.separator)) ? outDir + newFileName : outDir
					+ "/" + newFileName;
			try {
				out = new FileOutputStream(outPutPath);
			} catch (FileNotFoundException e) {
				return false;
			}

			int bytesRead;
			byte[] buffer = new byte[BUFFER];

			try {
				while ((bytesRead = in.read(buffer, 0, BUFFER)) != -1) {
					out.write(buffer, 0, bytesRead);
				}
			} catch (IOException e) {
				return false;
			} finally {
				try {
					in.close();
					out.close();
				} catch (IOException e2) {
				}
			}
			return true;
		} else
			return false;
	}

	/**
	 * 删除指定文件
	 * 
	 * @param filename
	 *            文件名
	 * @return 删除信息
	 */
	public static String deleteFile(String filename) {
		File file = new File(filename);
		if (file.isDirectory()) {
			return "not a file";
		}
		if (!file.exists()) {
			return "file is not exist";
		}
		return Boolean.toString(file.delete());
	}

	/**
	 * 文件名加上日期信息
	 * 
	 * @param fileName
	 * @return 文件名称
	 */
	public static String timeMark(String fileName) {
		String format = "yyyyMMddkkmmssSSS";
		SimpleDateFormat df = new SimpleDateFormat(format);
		String timeMark = df.format(new Date());

		int last = fileName.lastIndexOf(".");
		if (last == -1) {
			fileName = fileName + "." + timeMark;
		} else {
			fileName = fileName.substring(0, last) + "." + timeMark
					+ fileName.substring(last);
		}
		return fileName;
	}

	/**
	 * 文件名称长度限制
	 * 
	 * @param fileName
	 *            文件全名
	 * @param nameLimit
	 *            文件名长度
	 * @param extLimit
	 *            文件扩展名长度
	 * @return 文件名
	 */
	public static String nameLengthLimit(String fileName, int nameLimit,
			int extLimit) {
		nameLimit = (nameLimit < 8 && nameLimit != 0) ? 8 : nameLimit;
		extLimit = (extLimit < 3 && extLimit != 0) ? 3 : extLimit;

		int last = fileName.lastIndexOf(".");
		if (last != -1) {
			String name = fileName.substring(0, last);
			String ext = fileName.substring(last + 1);
			name = (nameLimit != 0 && name.length() > nameLimit) ? name
					.substring(0, nameLimit) : name;
			ext = (extLimit != 0 && ext.length() > extLimit) ? ext.substring(0,
					extLimit) : ext;

			fileName = name + "." + ext;
		} else {
			fileName = (nameLimit != 0 && fileName.length() > nameLimit) ? fileName
					.substring(0, nameLimit)
					: fileName;
		}

		return fileName;
	}

	/**
	 * 获取文件名
	 * 
	 * @param file
	 *            文件
	 * @param encoding
	 *            编码
	 * @return 文件名
	 */
	public static String getFileName(File file, String encoding) {
		if (file == null)
			return "";
		String fileName = file.getName();
		if (encoding != null) {
			try {
				fileName = new String(fileName.getBytes(), encoding);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return fileName;
	}

	/**
	 * 获取文件的扩展名
	 * 
	 * @param fileName
	 *            文件全名
	 * @return 文件扩展名
	 */
	public static String getExt(String fileName) {
		int last = fileName.lastIndexOf(".");
		if (last != -1)
			return fileName.substring(last + 1);
		else
			return "";
	}

	public static String removeExt(String fileName) {
		int last = fileName.lastIndexOf(".");
		if (last != -1)
			return fileName.substring(0, last);
		else
			return "";
	}

	/**
	 * 判断文件是否已存在
	 * 
	 * @param fileName
	 *            文件名
	 * @return 是否已存在
	 */
	public static boolean isExists(String fileName) {
		File file = new File(fileName);
		if (file.exists())
			return true;
		else
			return false;
	}

	/**
	 * 判断文件是否已存在
	 * 
	 * @param file
	 *            文件名
	 * @return 是否已存在
	 */
	public static boolean isExists(File file) {
		if (file.exists())
			return true;
		else
			return false;
	}

	/**
	 * 文件拷贝
	 * 
	 * @param src
	 *            源文件
	 * @param dest
	 *            目标文件
	 * @return 是否成功
	 * @throws IOException
	 *             读写异常
	 */
	public static boolean copyFile(File src, File dest) {
		int BUFF_SIZE = 100000;
		byte[] buffer = new byte[BUFF_SIZE];
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(dest);

			while (true) {
				synchronized (buffer) {
					int amountRead = in.read(buffer);

					if (amountRead == -1) {
						break;
					}

					out.write(buffer, 0, amountRead);
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 文件拷贝
	 * 
	 * @param src
	 *            源文件
	 * @param dest
	 *            目标文件
	 * @return 是否成功
	 * @throws IOException
	 *             读写异常
	 */
	public static boolean copyFile(String src, String dest) {
		int BUFF_SIZE = 100000;
		byte[] buffer = new byte[BUFF_SIZE];
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new FileInputStream(src);
			out = new FileOutputStream(dest);

			while (true) {
				synchronized (buffer) {
					int amountRead = in.read(buffer);

					if (amountRead == -1) {
						break;
					}

					out.write(buffer, 0, amountRead);
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
